import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import net.sf.jasperreports.view.JasperViewer;

import java.io.File;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 使用 list<pojo> 作为数据源，这样做的好处是：
 * 制作jsxml时，可以想象已经有pojo数据进行填充，无需做任何 计算，避免那些计算表达式
 * 不直接和db打交道
 * 可以对比 DataSourceJDBC
 */
public class DataSourceList {
    private static File CLASS_PATH_ROOT_DIR = null;
    private static final String jrxmlFile = "/jrxml/report6.jrxml";
    private static final String jasperFile = "/jrxml/report6.jasper";

    static {
        try {
            CLASS_PATH_ROOT_DIR = new File(DataSourceList.class.getResource("/").toURI());
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
    }


    public void createReport() {
        try {
            JasperCompileManager.compileReportToFile(CLASS_PATH_ROOT_DIR + jrxmlFile);
            JasperPrint jp;

            List<Person> list = new ArrayList<Person>();
            list.add(new Person("a1", "a2", "tel"));
            list.add(new Person("b1", "b2", "tel"));
            list.add(new Person("c1", "c2", "tel"));
            Map parameters = new HashMap();
            jp = JasperFillManager.fillReport(CLASS_PATH_ROOT_DIR + jasperFile, parameters, new JRBeanCollectionDataSource(list));
            JasperViewer jv = new JasperViewer(jp);
            jv.setVisible(true);
        } catch (JRException ex) {
            ex.printStackTrace();
        }
    }

    public static void main(String[] args) {
        new DataSourceList().createReport();
    }

}